package com.my.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.my.entity.Admin;
import com.my.entity.Setting;
import com.my.service.AdminService;
import com.my.service.SettingService;
import com.my.util.Rest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
public class LoginController {

    @Autowired
    private AdminService service;

    @Autowired
    private SettingService sService;

    @GetMapping(value = {"/", "login"})
    public String login() {
        return "login";
    }

    @PostMapping("login")
    public String login(String username, String password, Model model, HttpSession session) {
        Admin admin = service.getOne(new QueryWrapper<Admin>().eq("username", username).eq("password", SecureUtil.md5(username + password)));
        if(admin != null) {
            session.setAttribute("CURRENT_ADMIN", admin);
            return "redirect:/index";
        }
        model.addAttribute("err", "用户名或密码错误");
        return "login";
    }

    @GetMapping("index")
    public String index(Model model, HttpSession session) {
        model.addAttribute("user", session.getAttribute("CURRENT_ADMIN"));
        return "index";
    }

    @GetMapping("logout")
    public String logout(HttpSession session) {
        session.removeAttribute("CURRENT_ADMIN");
        return "login";
    }

    @GetMapping("systemSetting")
    public String systemSetting(Model model) {
        model.addAttribute("list", sService.list());
        return "systemSetting";
    }

    @PostMapping("/setting/edit")
    @ResponseBody
    public Rest edit(@RequestBody JSONObject setting) {
        for (String key : setting.keySet()) {
            sService.update(new UpdateWrapper<Setting>().set("setting_value", setting.getStr(key)).eq("setting_key", key));
        }
        return Rest.ok("修改成功！");
    }

}
